<template>
  <div class="flg-rate">
    <div class="header">
      <h1 class="title">
        <i class="iconfont icon-querycriteria"></i> 查询条件
      </h1>
      <div class="form-wrapper cargo-form no-valid">
        <el-form :inline="true" class="demo-form-inline">
          <el-row type="flex" align="middle">
            <el-col :span="4">
              <el-form-item label="时间">
                <el-date-picker
                  size="mini"
                  type="date"
                  v-model="queryForm.validdate"
                  placeholder="请选择日期"
                  format="yyyy年MM月dd日"
                  value-format="yyyy-MM-dd">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="目的站">
                <div class="form-content-muilt">
                  <u-input :max=3 v-model="queryForm.tostation"></u-input>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="航空公司">
                <u-input :max=3 v-model="queryForm.carrier"></u-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="航班">
                <u-input v-model="queryForm.shedfno" :onlyLetter="false"></u-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="货物种类">
                <el-input size="mini"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4" style="padding-left: 10px">
              <el-form-item>
                <el-button size="mini" type="primary" @click="list" :loading="queryLoading">查询</el-button>
                <el-button size="mini" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
    <div class="table-wrapper">
      <h1 class="title">
        运价列表
      </h1>
      <div class="btn-wrapper">
        <el-button size="mini" @click="save"> 新增</el-button>
        <el-button size="mini" @click="update"> 修改</el-button>
        <el-button size="mini" @click="remove">删除</el-button>
        <el-button size="mini">导入</el-button>
      </div>
      <div class="table">
        <el-table
          v-loading="tableLoading"
          :data="pageData"
          @row-click="clickRow"
          @selection-change="selectionChange"
          highlight-current-row
          border
          style="width: 100%">
          <el-table-column
            type="selection"
            width="55">
          </el-table-column>
          <el-table-column
            prop="date"
            label="代理人代码">
          </el-table-column>
          <el-table-column
            prop="dep"
            label="始发站">
          </el-table-column>
          <el-table-column
            prop="tostation"
            label="目的站">
          </el-table-column>
          <el-table-column
            prop="carrier"
            label="承运人">
          </el-table-column>
          <el-table-column
            prop="shedfno"
            label="航班号">
          </el-table-column>
          <el-table-column
            prop="spcode"
            label="特码">
          </el-table-column>
          <el-table-column
            prop="weightm"
            label="M">
          </el-table-column>
          <el-table-column
            prop="weightn"
            label="N">
          </el-table-column>
          <el-table-column
            prop="weight45"
            label="45">
          </el-table-column>
          <el-table-column
            prop="weight100"
            label="100">
          </el-table-column>
          <el-table-column
            prop="weight300"
            label="300">
          </el-table-column>
          <el-table-column
            prop="weight500"
            label="500">
          </el-table-column>
          <el-table-column
            prop="weight1000"
            label="1000">
          </el-table-column>
          <el-table-column
            prop="remarks"
            label="备注">
          </el-table-column>
          <div slot="empty">
            <i class="iconfont icon-bukaixin"></i> 暂无数据
          </div>
        </el-table>
        <div class="page-wrapper">
          <el-pagination
            background
            class="hy-pagination"
            v-show="tableData.length"
            :current-page.sync="currentPage"
            :page-size="5"
            layout="total, prev, pager, next"
            @current-change="handleCurrentChange"
            :total="tableData.length">
          </el-pagination>
        </div>
      </div>
    </div>
    <div class="detail-wrapper">
      <h1 class="title">
        详细信息
      </h1>
      <div class="btn-wrapper">
        <el-button size="mini" :disabled="disabledState" :loading="submitLoading" @click="submit">保存</el-button>
        <el-button size="mini" @click="cancel" :disabled="disabledState">取消</el-button>
      </div>
      <div class="form-wrapper cargo-form">
        <el-form :inline="true" ref="flgRateForm" :model="currentFormItem" :rules="rules">
          <el-row>
            <el-col :span="5">
              <el-form-item label="有效期(始)" prop="begindate">
                <el-date-picker
                  v-model="currentFormItem.begindate"
                  :clearable="false"
                  size="mini"
                  :disabled="disabledState || editState"
                  type="date"
                  placeholder="请选择日期"
                  format="yyyy年MM月dd日"
                  value-format="yyyy-MM-dd">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="有效期(终)" prop="enddate">
                <el-date-picker
                  :disabled="disabledState || editState"
                  :clearable="false"
                  v-model="currentFormItem.enddate"
                  size="mini"
                  type="date"
                  placeholder="请选择日期"
                  format="yyyy年MM月dd日"
                  value-format="yyyy-MM-dd">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="14">
              <el-form-item label="结算注意事项">
                <el-input :disabled="disabledState || editState" size="mini"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="5">
              <el-form-item label="始发站" prop="dep">
                <u-input :max="3" ref="firstInput" :disabled="disabledState" v-model="currentFormItem.dep"></u-input>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="目的站" prop="tostation">
                <u-input :max="3" :disabled="disabledState" v-model="currentFormItem.tostation"></u-input>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="承运人" prop="carrier">
                <u-input :max="3" :disabled="disabledState" v-model="currentFormItem.carrier"></u-input>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="航班" prop="shedfno">
                <u-input :disabled="disabledState" v-model="currentFormItem.shedfno"></u-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="特码" prop="spcode">
                <u-input :max="3" :disabled="disabledState" v-model="currentFormItem.spcode"></u-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="5">
              <el-form-item label="M" prop="weightm">
                <el-input size="mini" type="number" :disabled="disabledState" v-model="currentFormItem.weightm"
                          auto-complete="off"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="N" prop="weightn">
                <el-input size="mini" type="number" :disabled="disabledState"
                          v-model.number="currentFormItem.weightn"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="45" prop="weight45">
                <el-input size="mini" type="number" :disabled="disabledState"
                          v-model.number="currentFormItem.weight45"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="100" prop="weight100">
                <el-input size="mini" type="number" :disabled="disabledState"
                          v-model.number="currentFormItem.weight100"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="300" prop="weight300">
                <el-input size="mini" type="number" :disabled="disabledState"
                          v-model.number="currentFormItem.weight300"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="5">
              <el-form-item label="500" prop="weight500">
                <el-input size="mini" type="number" :disabled="disabledState"
                          v-model.number="currentFormItem.weight500"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="1000" prop="weight1000">
                <el-input size="mini" type="number" :disabled="disabledState"
                          v-model.number="currentFormItem.weight1000"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-input type="textarea" :disabled="disabledState" placeholder="备注"
                        v-model="currentFormItem.remarks"></el-input>
            </el-col>
          </el-row>
        </el-form>

      </div>
    </div>
  </div>
</template>

<script>
  import {formState} from 'common/js/config'
  import rateApi from 'api/rateManager'
  import UInput from 'base/uppercase-input/uppercase-input'
  import {tableLoadCb, updateCb, saveCb} from 'common/js/common'
  import {deepClone, pageData, formatDate} from 'common/js/util'
  import {mapGetters} from 'vuex'

  // 初始表单数据
  const defaultFormItem = {
    "ratetable": 'AFEE',
    // 开始日期
    "begindate": '',
    // 结束日期
    "enddate": '',
    // 起运港
    "dep": '',
    // 目的港
    "tostation": '',
    // 航空公司
    "carrier": '',
    // 航班号
    "shedfno": '',
    // 特码
    "spcode": '',
    "weightm": '',
    "weightn": '',
    "weight45": '',
    "weight100": '',
    "weight300": '',
    "weight500": '',
    "weight800": '',
    "weight1000": '',
    "remarks": ''
  }

  // 初始查询条件
  const defaultQueryForm = {
    validdate: formatDate(new Date(), 'yyyy-MM-dd'),
    tostation: '',
    carrier: '',
    shedfno: ''
  }

  // 完整的校验规则
  const baseRules = {
    begindate: [
      {required: true, message: '请选择日期', trigger: 'change'}
    ],
    enddate: [
      {required: true, message: '请选择日期', trigger: 'change'}
    ],
    dep: [
      {required: true, message: '请填写完整', trigger: 'blur'},
      {min: 3, max: 3, message: '长度为3', trigger: 'blur'}
    ],
    tostation: [
      {required: true, message: '请填写完整', trigger: 'blur'},
      {min: 3, max: 3, message: '长度为3', trigger: 'blur'}
    ],
    carrier: [
      {required: true, message: '请填写完整', trigger: 'blur'},
      {min: 2, max: 3, message: '长度为2到3', trigger: 'blur'}
    ],
    spcode: [
      {min: 3, max: 3, message: '长度为3', trigger: 'blur'}
    ]
  }

  export default {
    created() {
      this.list()
    },
    data() {
      return {
        // 表单新增 修改状态
        actionState: '',
        currentPage: 1,
        submitLoading: false,
        queryLoading: false,
        currentFormItem: deepClone(defaultFormItem),
        tableData: [],
        tableLoading: true,
        rules: deepClone(baseRules),
        selections: [],
        queryForm: deepClone(defaultQueryForm)
      }
    },
    methods: {
      // 获取数据
      list() {
        this.tableLoading = true
        rateApi.list(this.queryForm).then(res => {
          this.tableLoadCb(res)
        })
      },
      // 重置查询
      resetQuery() {
        this.queryForm = deepClone(defaultQueryForm)
        this.list()
        this.currentFormItem = deepClone(defaultFormItem)
      },
      // 新增数据
      save() {
        this._handlerSaveRules()
        this.actionState = formState.ADD
        let template = deepClone(defaultFormItem)
        template.optid = this.userInfo.optId,
          template.optname = this.userInfo.optName
        this.currentFormItem = template
        // dom节点的变化后的操作要写在nextTick里
        this.$nextTick(() => {
          this.$refs.firstInput.focus()
        })
      },
      // 编辑数据
      update() {
        if (!this.currentFormItem.manageid) {
          this.$message.warning('请单击选中要编辑的选项')
          return
        }
        this._handlerUpdateRules()
        this.actionState = formState.UPDATE
        this.$nextTick(() => {
          this.$refs.firstInput.focus()
        })
      },
      // 删除数据
      remove() {
        if (!this.selections.length) {
          this.$message.warning('请选中要删除的选项')
          return
        }
        this.$confirm('确认删除选中项?', '提示', {
          type: 'warning'
        }).then(() => {
          let ids = this.selections.map(val => val.manageid)
          rateApi.remove(ids).then(res => {
            saveCb(res, this.list, this.resetFlgForm)
          })
        })
      },
      // 提交表单
      submit() {
        // 补齐空费率
        this._padRate()
        this.$refs['flgRateForm'].validate((valid) => {
          if (valid) {
            this.actionState === formState.UPDATE ? this.updateAction() : this.saveAction()
          } else {
            this.$message.error('请检查输入')
            return false;
          }
        });
      },
      saveAction() {
        this.submitLoading = true
        rateApi.save(this.currentFormItem).then(res => {
          saveCb(res, this.list, this.resetFlgForm)
          this.submitLoading = false
          this.clearActionState()
        })
      },
      updateAction() {
        this.submitLoading = true
        rateApi.update(this.currentFormItem).then((res) => {
          updateCb(res, this.list)
          this.submitLoading = false
          this.clearActionState()
        })
      },
      // 取消编辑
      cancel() {
        if (this.actionState === formState.ADD) {
          this.resetFlgForm()
        }
        this.clearActionState()
      },
      // 改变分页
      handleCurrentChange(currentPage) {
        this.currentPage = currentPage
      },
      // 点击行
      clickRow(row) {
        this.clearActionState()
        this.currentFormItem = deepClone(row)
      },
      resetFlgForm() {
        this.currentFormItem = deepClone(defaultFormItem)
      },
      clearActionState() {
        this.actionState = ''
        this.$refs['flgRateForm'].clearValidate()
      },
      selectionChange(val) {
        this.selections = val
      },
      tableLoadCb(res) {
        res = res.data
        this.tableData = res.data
        this.tableLoading = false
      },
      _padRate() {
        const rateList = ["weightm", "weightn", "weight45", "weight100", "weight300", "weight500", "weight800", "weight1000"]
        // 第一项就为空 不执行函数
        if (!this.currentFormItem[rateList[0]]) return
        // 找到空值的标记
        let tag = false
        // 最后一个不为空的值
        let lastVal
        rateList.forEach((rate, index) => {
          // 第一次找到空值 记录下来最后非空的值 把标记置为ture
          if (!this.currentFormItem[rate] && !tag) {
            lastVal = this.currentFormItem[rateList[index - 1]]
            tag = true
          }
          // 标记为true 后面的每个值都赋值为lastVal
          if (tag) {
            this.currentFormItem[rate] = lastVal
          }
        })
      },
      // 编辑时的校验规则
      _handlerUpdateRules() {
        this.rules.begindate = ''
        this.rules.enddate = ''
      },
      // 新增时的校验规则
      _handlerSaveRules() {
        this.rules.begindate = [
          {required: true, message: '请选择日期', trigger: 'change'}
        ]
        this.rules.enddate = [
          {required: true, message: '请选择日期', trigger: 'change'}
        ]
      }
    },
    computed: {
      // 表单禁用状态
      disabledState() {
        return !(this.actionState === formState.ADD || this.actionState === formState.UPDATE)
      },
      // 编辑时候也禁用的输入框
      editState() {
        return this.actionState === formState.UPDATE
      },
      // 根据页数显示的表格数据
      pageData() {
        return pageData(this.tableData, this.currentPage)
      },

      ...mapGetters([
        'userInfo'
      ])
    },
    components: {
      UInput
    }
  }
</script>

<style lang="stylus" scoped>
  @import "~common/stylus/variable.styl"

  .flg-rate
    .header
      padding 20px
      background $color-panel
      margin-bottom 20px
      .title
        padding-bottom 10px
        font-weight 700
      .form-wrapper
        background $color-panel-grey
        overflow-x auto
        padding 10px
        margin 0 10px
    .table-wrapper
      padding 20px
      background $color-panel
      margin-bottom 20px
      .title
        padding-bottom 0 10px
        font-weight 700
      .btn-wrapper
        padding 10px
      .table
        padding 0 10px
        .page-wrapper
          display flex
          justify-content flex-end
          padding 20px 10px 0
    .detail-wrapper
      padding 20px
      background $color-panel
      .title
        font-weight 700
      .btn-wrapper
        padding 10px
      .form-wrapper
        background $color-panel-grey
        padding 10px
        margin 0 10px
</style>
